﻿using PBO.Data;
using PBO.Game.BattleLog;
using PokemonBattle.BattleNetwork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PBO.Game.BattleClass
{
    /// <summary>
    /// One Player
    /// </summary>
    public class BattleTeam
    {
        public int Id { get; private set; }
        public string PlayerName { get; private set; }
        public BattleGroup Group { get; private set; }
        public List<Pokemon> Pokemons { get; private set; }

        public Random random { get { return this.Group.Battle._random; } }
        public ILogBuilder log { get { return this.Group.Battle.log; } }
        public BattleGround ground { get { return this.Group.Battle.Ground; } }

        public BattleTeam(BattleGroup group, int id, string name, TeamData team)
        {
            this.Id = id;
            this.PlayerName = name;
            this.Group = group;
            this.Pokemons = new List<Pokemon>();
            foreach (var pm in team.Pokemons)
            {
                if (pm.IsEmpty)
                {
                    this.Pokemons.Add(null);
                }
                else
                {
                    Pokemon newPM = new Pokemon(pm, this, Group.Battle.Rules.Contains(BattleRule.PPUp));
                    this.Pokemons.Add(newPM);
                }
            }

            foreach (Pokemon pm in SelectedPokemon)
            {
                pm.BattleState = new PokemonBattleState();
                this.Group.AddPokemonHandler(pm);
            }
        }

        #region SelectedPokemons

        public int SelectedCount
        {
            get { return Group.Battle.Mode == BattleMode.Double ? 2 : 1; }
        }

        public IEnumerable<Pokemon> SelectedPokemon
        {
            get
            {
                return Pokemons.Take(SelectedCount);
                //yield return Pokemons[0];
                //if (this.Group.Battle.Mode == BattleMode.Double)
                //{
                //    yield return Pokemons[1];
                //}
            }
        }

        public IEnumerable<Pokemon> CanChangePokemons
        {
            get
            {
                return this.Pokemons.Skip(SelectedCount).Where(p => p != null && p.HealthPower > 0);
            }
        }

        #endregion

        public void SwapPokemon(Pokemon p1, Pokemon p2)
        {
            int i = this.Pokemons.IndexOf(p1);
            int j = this.Pokemons.IndexOf(p2);
            Pokemon temp = p1;
            this.Pokemons[i] = p2;
            this.Pokemons[j] = temp;
        }
    }
}
